/*子应用*/
const express = require("express")
const query = require("../pool")
const sms = require("../modules/login/smscode") //导入短信模块
const jwt = require("../modules/token") //导入token模块

const login = express.Router()

// 获取用户数据

// 账号密码登录
login.post("/", async (req, res, next) => {
  let obj = req.body
  // console.log(obj);
  let user = await query(
    "select uid,user_icon,user_role from cake_user where uname = ? and upwd = md5(?)",
    [obj.uname, obj.upwd]
  )
  // //console.log(user)
  // console.log( [obj.uname, obj.upwd],rows)
  if (user.length == 0) {
    res.send({ code: 0, msg: "用户名不存在或密码错误" })
  } else {
    let token = jwt.getToken(user[0].uid, user[0].user_icon)
    await query("update cake_user set token = ? where uname = ?", [
      jwt.token,
      obj.uname,
    ])
    res.send({ code: 1, msg: "登录成功", data: { user }, token })
  }
})

// 获取验证码
login.get("/mobile?:phone", async (req, res) => {
  let obj = req.query
  // console.log(req.query.phone)
  // 查询系统是否存在该手机号
  let sql = "select 1 from cake_user where phone = ? and upwd is not null"
  let rows = await query(sql, [obj.phone])
  if (rows.length == 0) {
    res.send({ code: 0, msg: "该手机号不存在,请注册" })
  } else {
    let smscode = await sms(obj.phone)
    let result = await query(
      "update cake_user set logincode = ? where phone = ?",
      [smscode, obj.phone]
    )
    if (result.affectedRows == 0) {
      res.send({ code: 0, msg: "数据插入失败" })
    } else {
      res.send({ code: 1, msg: "验证码插入数据成功" })
    }
  }
})

// 验证码登录
login.post("/codeLogin", async (req, res) => {
  let obj = req.body
  // 手机用户登录验证
  let sql = "select 1 from cake_user where phone = ? and logincode = ?"
  let rows = await query(sql, [obj.phone, obj.telCode])
  let userData = await query(
    "select uid,uname,user_icon,user_role from cake_user where phone = ?",
    [obj.phone]
  )
  // console.log(rows)
  if (rows.length == 0) {
    res.send({ code: 0, msg: "验证码不正确" })
  } else {
    let token = jwt.getToken(userData[0].uid,userData[0].user_icon)
    await query("update cake_user set token = ? where phone = ?", [
      jwt.token,
      obj.phone,
    ])
    res.send({ code: 1, msg: "登录成功", data: userData, token })
  }
})

// 验证token
login.get("/verify?:token", async (req, res) => {
  let obj = req.query
  console.log(obj.token)
  // token验证结果
  let result = jwt.verifytoken(obj.token)
  console.log(JSON.stringify(result)=='{}')
  if (JSON.stringify(result)=='{}') {
    res.send({ code: 0, msg: "token无效" })
  } else {
    let sql = "select uname,user_icon,user_role from cake_user where uid = ?"
    let params = [result.uid]
    // console.log(params)
    let uname = await query(sql, params)
    // console.log(uname)
    res.send({ code: 1, data: uname })
  }
})
//暴露
module.exports = login
